package com.kaifamiao.resp;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet( "/show/image" )
public class ShowImageServlet extends HttpServlet {

    @Override
    protected void doGet( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        // 设置响应头( response header )
        // response.setContentType( "image/jpeg" );
        response.setHeader( "content-type" , "image/jpeg" );
        response.setHeader( "content-disposition" , "inline" );

        // 获得可以向 "响应对象" 输出字节数据的 输出流
        ServletOutputStream out = response.getOutputStream();

        // 首先尝试使用字节输入流读取一副图片
        InputStream in = new FileInputStream( "D:/upload/fengjie.jpg" );

        int n ;
        byte[] buffer = new byte[ 1 << 20 ];
        while( ( n = in.read( buffer ) ) != -1 ){
            // 向 "响应对象" 中输出 字节数据
            out.write( buffer , 0 , n );
        }

        in.close();
    }

    @Override
    protected void doPost( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {
        throw new IllegalStateException( "想看图片就要用GET请求哦" );
    }

}
